package cm.iccsoft.android.telecomcost.ui;

import java.util.ArrayList;

import cm.iccsoft.android.telecomcost.DatabaseManager;
import cm.iccsoft.android.telecomcost.R;
import cm.iccsoft.android.telecomcost.TelecomCost;
import cm.iccsoft.android.telecomcost.activities.CountryListActivity;
import cm.iccsoft.android.telecomcost.entities.Country;
import cm.iccsoft.android.telecomcost.entities.Zone;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class CountryDialog extends Dialog {

	private DatabaseManager db;
	private EditText txtName;
	private Zone _zone = null;
	private Spinner zones_list;
	private EditText txtCode;
	private ArrayList<Zone> zones;
	private Country _country;
	private Context _context;
	private Button btnSaveCountry;
	private Button btnCloseCountryDialog;
	private boolean shouldRefreshCountryList = false;

	/**
	 * @param context
	 * @param cancelable
	 * @param cancelListener
	 */
	public CountryDialog(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		_context = context;
	}

	/**
	 * @param context
	 * @param theme
	 */
	public CountryDialog(Context context, int theme) {
		super(context, theme);
		_context = context;
	}

	public CountryDialog(Context context, Country country) {
		super(context);
		_country = country;
		_context = context;
	}

	private void saveCountry() {
		if (_zone == null) {
			Toast.makeText(_context, "Please select a zone for the country", 3)
					.show();
		} else {
			String name = txtName.getText().toString();
			String code = txtCode.getText().toString();

			if (name.equals("") || code.equals("")) {
				Toast.makeText(getOwnerActivity(),
						"Please enter the name of the country and the code", 3)
						.show();
			} else {				
				Country country = ((CountryListActivity) _context)
				.getCountry(name);
				
				if (_country == null && country != null) {					
					Toast.makeText(getOwnerActivity(),
							"A country with the same name already exists",
							3).show();
					return;
				}
				
				if (_country != null && country != null) {	
					if(_country.getId() != country.getId())
					{
						Toast.makeText(getOwnerActivity(),
								"A country with the same name already exists",
								3).show();
						return;
					}					
				}

				long id = _country == null ? -1 : _country.getId();
				_country = _country == null ? new Country() : _country;								

				_country.setId(id == -1 ? db.getNextId() : id);
				_country.setName(name);
				_country.setCode(code);
				_country.setZoneId(_zone.getId());																				
				
				shouldRefreshCountryList = true;
				Toast.makeText(_context,db.saveCountry(_country,_zone,id) ? "Country saved !!!" : "could not save this country", 3)
						.show();
				id = _country.getId();	
				resetDialog();
			}
		}
	}

	private void setZone() {
		if (_country != null) {
			Log.i("EditCountryDialog",
					"selecting zone for country " + _country.getName());
			int index = 0;
			while (index < zones.size()) {
				if (zones.get(index).getId() == _country.getZoneId()) {
					zones_list.setSelection(index);
					index = zones.size();
				}

				index++;
			}
		}
	}

	public void setCountry(Country country) {
		_country = country;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("EditCountryDialog", "Creating the dialog...");
		super.onCreate(savedInstanceState);

		db = TelecomCost.getDatabaseManager();
		setContentView(R.layout.edit_country);
		setTitle("Edit a Country");

		btnSaveCountry = (Button) findViewById(R.id.btnSaveCountry);
		btnCloseCountryDialog = (Button) findViewById(R.id.btnCloseCountryDialog);
		txtName = (EditText) findViewById(R.id.txtCountryName);
		txtCode = (EditText) findViewById(R.id.txtCountryCode);

		txtName.setText(_country != null ? _country.getName() : "");
		txtCode.setText(_country != null ? _country.getCode() : "");

		btnSaveCountry.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				saveCountry();
			}
		});

		btnCloseCountryDialog.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				closeDialog();
			}
		});

		zones_list = (Spinner) findViewById(R.id.spinner1);

		zones_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				selectZone(arg2);
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}
		});

		zones = db.getZones();
		ArrayAdapter<Zone> adapter = new ArrayAdapter<Zone>(_context,
				android.R.layout.simple_spinner_item, zones);
		zones_list.setAdapter(adapter);
		setZone();
		Log.i("EditCountryDialog", "Dialog ohne bundle created....");
	}

	protected void closeDialog() {
		Log.i("EditCountryDialog", "hiding the dialog");
		hide();
		if (shouldRefreshCountryList) {
			((CountryListActivity) _context).bindCountries();
		}
		shouldRefreshCountryList = false;
		_country = null;
	}

	protected void selectZone(int position) {
		_zone = zones.get(position);
		Log.i("DIALOG_NEW_COUNTRY", "Zone " + zones.get(position).getName()
				+ " selected");
	}

	public void resetDialog() {
		Log.i("EditCountryDialog", "reseting the dialog...");
		_country = null;
		txtName.setText("");
		txtCode.setText("");
	}

	@Override
	public void show() {
		Log.i("EditCountryDialog", "showing the dialog...");
		super.show();
		txtName.setText(_country != null ? _country.getName() : "");
		txtCode.setText(_country != null ? _country.getCode() : "");
		Log.i("EditCountryDialog", "dialog on screen...");
	}

	@Override
	protected void onStart() {
		Log.i("EditCountryDialog", "Starting the dialog...");
		super.onStart();
		Log.i("EditCountryDialog", "dialog started...");
	}

	@Override
	protected void onStop() {
		Log.i("EditCountryDialog", "Stopping the dialog...");
		super.onStop();
		Log.i("EditCountryDialog", "dialog stopped...");
	}

}
